package com.sky.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author 陈俊宇
 * * @date 2025/9/17
 */
@Aspect
@Component
@Slf4j
public class BookAdvice {





    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 前置通知：记录开始时间
     */
    @Before("execution(* com.sky.controller.admin.EmployeeController.page(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        log.info("【前置通知】开始执行员工分页查询，时间戳：{}", startTime.get());
    }

    /**
     * 后置通知：记录方法返回结果和执行时间
     * @param joinPoint 连接点信息
     * @param result 方法返回值
     */
    @AfterReturning(
            pointcut = "execution(* com.sky.controller.admin.EmployeeController.page(..))",
            returning = "result"
    )
    public void afterReturningMethod(JoinPoint joinPoint, Object result) {
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime.get();

        log.info("【后置通知】员工分页查询执行完成");
        log.info("【后置通知】方法签名：{}", joinPoint.getSignature().toShortString());
        log.info("【后置通知】返回结果：{}", result);
        log.info("【后置通知】执行耗时：{} 毫秒", executionTime);

        // 清除ThreadLocal
        startTime.remove();
    }

//    //统计目标方法的耗时时间
//    @Around("execution(* com.sky.controller.admin.EmployeeController.page(..))")
//    public Object method(ProceedingJoinPoint joinPoint) throws Throwable {
//
//        long star = System.nanoTime();
//        Object result = joinPoint.proceed();
//        long end = System.nanoTime();
//        System.out.println("目标方法"+joinPoint.toShortString() +"耗时：" + ((end - star) )+ "纳秒");
//        return result;
//    }
}
